(function($) {
$.fn.galleryView = function(options) {
  var opts = $.extend($.fn.galleryView.defaults, options);
  opts = $.extend(true, {}, opts);
  
  var id;
  var iterator = 0;
  
  var gallery_width;
  var gallery_height;
  
  var frame_margin = 10;
  
  var strip_width;
  var wrapper_width;
  
  var item_count = 0;
  
  var slide_method;
  
  var img_path;
  
  var paused = false;
  
  var frame_caption_size = 20;
  var frame_margin_top = 5;
  
  var pointer_width = 0;
  
  //Define jQuery objects for reuse
  var j_gallery;
  var j_filmstrip;
  var j_frames;
  var j_panels;
  var j_pointer;
  
  /************************************************/
  /* Plugin Methods */
  /************************************************/
  function showItem(i) {
    //Disable next/prev buttons until transition is complete
    $('img.nav-next' + opts.unique).unbind('click');
    $('img.nav-prev' + opts.unique).unbind('click');
    
    j_frames.unbind('click');
    
    if(has_panels) {
      if(opts.fade_panels) {
        //Fade out all panels and fade in target panel
        j_panels.fadeOut(opts.transition_speed).eq(i%item_count).fadeIn(opts.transition_speed);
      }
    }
    
    if(has_filmstrip) {
      //Slide either pointer or filmstrip, depending on transition method
      if(slide_method == 'strip') {
        //Stop filmstrip if it's currently in motion
        j_filmstrip.stop();
        //Determine distance between pointer (eventual destination) and target frame
        var distance = getPos(j_frames[i]).left - (getPos(j_pointer[0]).left);
        var leftstr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
        //Animate filmstrip and slide target frame under pointer
        //If target frame is a duplicate, jump back to 'original' frame
        j_filmstrip.animate({ 'left': leftstr }, opts.transition_speed, opts.easing, function() { //Always ensure that there are a sufficient number of hidden frames on either
                                                                                                  //side of the filmstrip to avoid empty frames
                                                                                                  if(i>item_count) {
                                                                                                    i = i % item_count;
                                                                                                    iterator = i;
                                                                                                    j_filmstrip.css('left', '-' + ((opts.frame_width + frame_margin) * i) + 'px');
                                                                                                  } else if (i <= (item_count - strip_size)) {
                                                                                                    i = (i % item_count) + item_count;
                                                                                                    iterator = i;
                                                                                                    j_filmstrip.css('left', '-' + ((opts.frame_width + frame_margin) * i) + 'px');
                                                                                                  }
                                                                                                  
                                                                                                  if(!opts.fade_panels) {
                                                                                                    j_panels.hide().eq(i%item_count).show();
                                                                                                  }
                                                                                                  $('img.nav-prev'+opts.unique).click(showPrevItem);
                                                                                                  $('img.nav-next'+opts.unique).click(showNextItem);
                                                                                                  enableFrameClicking();
                                                                                                });
      } else if(slide_method=='pointer') {
        //Stop pointer if it's currently in motion
        j_pointer.stop();
        //Get position of target frame
        var pos = getPos(j_frames[i]);
        //Slide the pointer over the target frame
        j_pointer.animate({ 'left':(pos.left-2+'px') }, opts.transition_speed, opts.easing, function() { if(!opts.fade_panels) {
                                                                                                           j_panels.hide().eq(i%item_count).show();
                                                                                                         }
                                                                                                         $('img.nav-prev'+opts.unique).click(showPrevItem);
                                                                                                         $('img.nav-next'+opts.unique).click(showNextItem);
                                                                                                         enableFrameClicking();
                                                                                                       });
      }
      if($('a',j_frames[i])[0]) {
        j_pointer.unbind('click').click(function() { var a = $('a', j_frames[i]).eq(0);
                                                     if(a.attr('target') == '_blank') { window.open(a.attr('href')); }
                                                     else {location.href = a.attr('href');}
                                                   });
      }
    }
  };
  
  function showNextItem() {
    $(document).stopTime('transition' + opts.unique);
    if(++iterator == j_frames.length) { iterator = 0; }
    showItem(iterator);
    $(document).everyTime(opts.transition_interval, 'transition' + opts.unique, function() { showNextItem(); });
  };
  
  function showPrevItem() {
    $(document).stopTime('transition' + opts.unique);
    if(--iterator < 0) { iterator = item_count - 1; }
    //alert(iterator);
    showItem(iterator);
    $(document).everyTime(opts.transition_interval,'transition' + opts.unique, function() { showNextItem(); });
  };
  
  function getPos(el) {
    var left = 0, top = 0;
    var el_id = el.id;
    if(el.offsetParent) {
      do {
        left += el.offsetLeft;
        top += el.offsetTop;
      } while(el = el.offsetParent); 
    }
    //If we want the position of the gallery itself, return it
    if(el_id == id) { return { 'left': left, 'top': top }; }
    //Otherwise, get position of element relative to gallery
    else {
      var gPos = getPos(j_gallery[0]);
      var gLeft = gPos.left;
      var gTop = gPos.top;
      return {'left':left-gLeft,'top':top-gTop};
    }
  };
  
  function enableFrameClicking() {
    j_frames.each(function(i) { $(this).click(function(){ $(document).stopTime('transition'+opts.unique);
                                                          showItem(i);
                                                          iterator = i;
                                                          $(document).everyTime(opts.transition_interval, 'transition' + opts.unique, function() { showNextItem(); });
                                                        });
                              });
  };
  
  function buildPanels() {
    j_panels.css({ 'width': (opts.panel_width - parseInt(j_panels.css('paddingLeft').split('px')[0], 10) - parseInt(j_panels.css('paddingRight').split('px')[0], 10)) + 'px', 
                   'height': (opts.panel_height - parseInt(j_panels.css('paddingTop').split('px')[0], 10) - parseInt(j_panels.css('paddingBottom').split('px')[0], 10)) + 'px'
                    });
  };
  
  function buildFilmstrip() {
    //Add wrapper to filmstrip to hide extra frames
    j_filmstrip.wrap('<div class="strip_wrapper'+opts.unique+'"></div>');
    if (slide_method == 'strip') {
      j_frames.clone().appendTo(j_filmstrip);
      j_frames.clone().appendTo(j_filmstrip);
      j_frames = $('li',j_filmstrip);
    }
    
    j_filmstrip.css({ 'width': strip_width+'px',
                      'height': (opts.frame_height+10) + 'px'
                    });
    j_frames.css({ 
                   'height':opts.frame_height+'px'
                 });
    
    $('.strip_wrapper' + opts.unique, j_gallery).css({ 'position':'absolute',
                                                       'top':opts.panel_height+'px',
                                                       'left':'0px',
                                                       'width':opts.panel_width+'px',
                                                       'height':(opts.frame_height+frame_margin_top+(opts.show_captions?frame_caption_size:frame_margin_top))+'px',
                                                       'overflow':'hidden'
                                                     });

    var pointer = $('<div></div>');
    pointer.attr('class','pointer' + opts.unique).appendTo(j_gallery).css({ 'position': 'absolute',
                                                                            'zIndex': '1000',
                                                                            'cursor': 'pointer',
                                                                            'top':getPos(j_frames[0]).top + 'px',
                                                                            'left': '0px',
                                                                            'height':opts.frame_height + 'px',
                                                                            'width':opts.frame_width + 'px'
                                                                          });
    j_pointer = $('.pointer' + opts.unique, j_gallery);
    if(has_panels) {
      var pointerArrow = $('<img />');
      pointerArrow.attr('src','plugins/ivqm/assets/border.png').appendTo(j_pointer).css({
        'height':opts.frame_height + 'px',
        'width':opts.frame_width + 'px'
      });
    }
    
    //If the filmstrip is animating, move the strip to the middle third
    if(slide_method == 'strip') {
      j_filmstrip.css('left','-'+((opts.frame_width+frame_margin)*item_count)+'px');
      iterator = item_count;
    }
    
    //Add navigation buttons
    if(opts.pre_nex_btn) {
      $('<img />').addClass('nav-next' + opts.unique).attr('src', 'plugins/ivqm/assets/nex.png').appendTo(j_gallery).css({ 'position': 'absolute',
                                                                                                                   'cursor': 'pointer',
                                                                                                                   'top': (opts.filmstrip_position == 'top' ? 0 : opts.panel_height / 2 - 25) + 'px',
                                                                                                                   'right': '0px'
                                                                                                                 }).click(showNextItem);
      $('<img />').addClass('nav-prev' + opts.unique).attr('src', 'plugins/ivqm/assets/pre.png').appendTo(j_gallery).css({ 'position': 'absolute',
                                                                                                                   'cursor': 'pointer',
                                                                                                                   'top': (opts.filmstrip_position == 'top' ? 0 : opts.panel_height / 2 - 25) + 'px',
                                                                                                                   'left': '0px'
                                                                                                                 }).click(showPrevItem);
    }
  };
  
  //Check mouse to see if it is within the borders of the panel
  //More reliable than 'mouseover' event when elements overlay the panel
  function mouseIsOverPanels(x, y) {
    var pos = getPos(j_gallery[0]);
    var top = pos.top;
    var left = pos.left;
    return x > left && x < left+opts.panel_width && y > top && y < top+opts.panel_height;
  };
  
  /************************************************/
  /* Main Plugin Code */
  /************************************************/
  return this.each(function() { j_gallery = $(this);
                                //Hide gallery to prevent Flash of Unstyled Content (FoUC) in IE
                                j_gallery.css('visibility', 'hidden');
                                //Assign elements to variables for reuse
                                j_filmstrip = $('.filmstrip_'+opts.unique,j_gallery);
                                j_filmstrip.addClass('gallery_filmstrip');
                                j_frames = $('li',j_filmstrip);
                                j_panels = $('.panel_'+opts.unique,j_gallery);
                                j_panels.addClass('gallery_panel');
                                id = j_gallery.attr('id');
                                has_panels = j_panels.length > 0;
                                has_filmstrip = j_frames.length > 0;
                                if (!has_panels) opts.panel_height = 0;
                                //Number of frames in filmstrip
                                item_count = has_panels?j_panels.length:j_frames.length;
                                strip_size = has_panels?6:Math.min(item_count,opts.filmstrip_size);
                                /************************************************/
                                /* Determine transition method for filmstrip */
                                /************************************************/
                                //If more items than strip size, slide filmstrip
                                //Otherwise, slide pointer
                                if(strip_size >= item_count) {
                                  slide_method = 'pointer';
                                  strip_size = item_count;
                                } else { slide_method = 'strip'; }
                                /************************************************/
                                /* Determine dimensions of various elements */
                                /************************************************/
                                //Width of gallery block
                                gallery_width = has_panels ? opts.panel_width : (strip_size*(opts.frame_width+frame_margin))-frame_margin+64;
                                //Height of gallery block = screen + filmstrip + captions (optional)
                                gallery_height = (has_panels ? opts.panel_height : 0) + (has_filmstrip ? opts.frame_height + frame_margin_top + (opts.show_captions ? frame_caption_size : frame_margin_top) : 0);
                                //Width of filmstrip
                                if  (slide_method == 'pointer') { strip_width = (opts.frame_width * item_count) + (frame_margin * (item_count)); }
                                else { strip_width = (opts.frame_width * item_count * 3) + (frame_margin * (item_count * 3)); }
                                //Width of filmstrip wrapper (to hide overflow)
                                /************************************************/
                                /* Apply CSS Styles */
                                /************************************************/
                                j_gallery.css({ 'position':'relative',
                                                'margin':'0',
                                                'background':opts.background_color,
                                                'border':opts.border,
                                                'width':gallery_width+'px',
                                                'height':gallery_height+'px'
                                              });
                                
                                /************************************************/
                                /* Build filmstrip and/or panels */
                                /************************************************/
                                if(has_filmstrip) {
                                  buildFilmstrip();
                                }
                                if(has_panels) {
                                  buildPanels();
                                }
                                /************************************************/
                                /* Add events to various elements */
                                /************************************************/
                                if(has_filmstrip) enableFrameClicking();
                                $().mousemove(function(e) { if(mouseIsOverPanels(e.pageX,e.pageY)) {
                                                              if(opts.pause_on_hover) {
                                                                $(document).oneTime(500, "animation_pause", function(){ $(document).stopTime('transition'+opts.unique);
                                                                                                                        paused = true;
                                                                                                                      });
                                                              }
                                                              if(has_panels && !has_filmstrip) {
                                                                $('.nav-overlay').fadeIn('fast');
                                                                $('.nav-next'+opts.unique).fadeIn('fast');
                                                                $('.nav-prev'+opts.unique).fadeIn('fast');
                                                              }
                                                            } else {
                                                              if(opts.pause_on_hover) {
                                                                $(document).stopTime("animation_pause");
                                                                if(paused) {
                                                                  $(document).everyTime(opts.transition_interval, 'transition' + opts.unique, function(){ showNextItem(); });
                                                                  paused = false;
                                                                }
                                                              }
                                                              
                                                              if(has_panels && !has_filmstrip) {
                                                                $('.nav-overlay').fadeOut('fast');
                                                                $('.nav-next'+opts.unique).fadeOut('fast');
                                                                $('.nav-prev'+opts.unique).fadeOut('fast');
                                                              }
                                                            }
                                            });
                                /************************************************/
                                /* Initiate Automated Animation */
                                /************************************************/
                                //Show the first panel
                                j_panels.eq(0).show();
                                //If we have more than one item, begin automated transitions
                                if(item_count > 1) {
                                  $(document).everyTime(opts.transition_interval,'transition'+opts.unique,function(){ showNextItem(); });
                                }
                                //Make gallery visible now that work is complete
                                j_gallery.css('visibility','visible');
                  });
  };
  
  $.fn.galleryView.defaults = {
    panel_width: 400,
    panel_height: 300,
    frame_width: 80,
    frame_height: 80,
    filmstrip_size: 1,
    overlay_height: 70,
    overlay_font_size: '1em',
    transition_speed: 500,
    transition_interval: 5000,
    overlay_opacity: 0.6,
    overlay_color: 'black',
    background_color: '#fff',
    overlay_text_color: 'white',
    caption_text_color: 'white',
    nav_theme: 'light',
    easing: 'swing',
    filmstrip_position: 'bottom',
    overlay_position: 'bottom',
    show_captions: false,
    fade_panels: false,
    pause_on_hover: false
  };
})(jQuery);